using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace ECatalog.Models.Shops
{
    public class ShopRepository : IShopRepository
    {
        public void Delete(int shopId)
        {
            using (var db = new DbContainer())
            {
                var shop = db.Shops.SingleOrDefault(s=>s.ShopId == shopId);
                db.Shops.Remove(shop);
                db.SaveChanges();
            }
        }

        public Shop GetActiveShop()
        {
            using (var db = new DbContainer())
            {
                var serverParams = db.ServerParams.FirstOrDefault();
                if (serverParams != null && serverParams.ShopId != null)
                {
                    return db.Shops.SingleOrDefault(s => s.ShopId == serverParams.ShopId.Value);
                }
            }
            return null;
        }

        Shop[] IShopRepository.All()
        {
            using (var db = new DbContainer())
            {
                return db.Shops.Include("Organization").ToArray();
            }
        }

        public Shop Add(Shop shop)
        {
            using (var db = new DbContainer())
            {
                db.Shops.Add(shop);
                db.SaveChanges();
                return shop;
            }
        }

        public Shop GetShop(int id)
        {
            using (var db = new DbContainer())
            {
                return db.Shops.FirstOrDefault(sh=>sh.ShopId==id);
            }
        }

        public void SaveShop(Shop shop)
        {
            using (var db = new DbContainer())
            {
                db.Entry(shop).State = EntityState.Modified;
                db.SaveChanges();
            }
        }
    }
}